<template>
  <el-dialog
    destroy-on-close
    width="700px"
    top="64px"
    class="user-dialog"
    append-to-body
    :title="`${currentRowObj ? '修改' : '新增'}`"
    :close-on-click-modal="false"
    :visible="dialogVisible"
    @close="close"
  >
    <div v-loading="wrapperLoading">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-suffix=":"
        label-position="top"
      >
        <title-line title="用户基本信息" class="mb15" />
        <el-row :gutter="20" type="flex" class="wrap">
          <el-col :span="12">
            <el-form-item label="登录名" prop="userName">
              <el-input
                v-model="ruleForm.userName"
                placeholder="请输入"
                :disabled="isCheck || !!currentRowObj"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickName">
              <el-input v-model="ruleForm.nickName" placeholder="请输入" :disabled="isCheck" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="dept">
              <input-tree-select
                v-model="ruleForm.dept"
                :disabled="isCheck"
                type="organize"
                :loadTreeApi="OrganizeTree"
                :props="{ value: 'id', label: 'shortName' }"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="ruleForm.phone" placeholder="请输入" :disabled="isCheck" />
            </el-form-item>
          </el-col>

          <!--<el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email" placeholder="请输入" :disabled="isCheck" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="ruleForm.gender" :disabled="isCheck">
                <el-radio label="1">男</el-radio>
                <el-radio label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>-->
        </el-row>

        <title-line title="角色权限配置" class="mb15" />

        <!-- 选择角色 -->
        <el-form-item prop="routerName">
          <add-role v-if="dialogVisible" ref="addRole" :isCheck="isCheck" />
        </el-form-item>

        <title-line title="数据权限" class="mb15" />

        <el-radio-group v-model="userPermObj.type" :disabled="isCheck" @change="radioChange">
          <el-radio
            v-for="(item, index) in dataPermissionTypeOptions"
            :key="index"
            :label="item.value"
            :class="{
              'last-label': index === dataPermissionTypeOptions.length - 1,
            }"
            >{{ item.name }}</el-radio
          >
          <el-button v-if="userPermObj.type === '4'" type="text" class="ptb0" @click="doModify">{{
            isCheck ? "查看" : "修改"
          }}</el-button>
        </el-radio-group>
      </el-form>
    </div>

    <!-- 数据权限弹窗 -->
    <data-access-dialog
      :dialogVisible.sync="dataAccessDialogVisible"
      :dataAccessChecked="dataAccessChecked"
      :currentAppObj="currentAppObj"
      :isCheck="isCheck"
      @success="dataAccessSuccess"
    />

    <span slot="footer">
      <template v-if="!isCheck">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="btnLoading" @click="submitData">确定</el-button>
      </template>
    </span>
  </el-dialog>
</template>

<script>
import dialogMixin from "mixins/dialogMixin";
import areaTreeMixin from "mixins/areaTreeMixin";
import rules from "./config/rules";
import { DictKeys } from "api/sys/dict";
import { UserAdd, UserDetail, UserUpdate } from "api/sys/user";
import AddRole from "./../add-role";
import DataAccessDialog from "./components/data-access-dialog";
import { OrganizeTree } from "api/sys/organize";

export default {
  components: { AddRole, DataAccessDialog },
  mixins: [dialogMixin, areaTreeMixin],
  props: {
    // 当前行数据
    currentRowObj: {
      type: Object,
      default: () => ({}),
    },
    // 是否为查看
    isCheck: {
      type: Boolean,
      default: false,
    },
    // 选中的部门数据
    deptStr: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      ruleForm: {
        // 登录名
        userName: "",
        // 姓名
        nickName: "",
        // 所属部门
        deptId: "",
        // 所属部门汉字
        deptName: "",
        // 手机号码
        phone: "",
        // 邮箱
        email: "",
        // 性别
        gender: "1",
        // 备注
        remarks: "",
        // 部门
        dept: "",
      },
      rules,
      // 数据权限
      userPermObj: {
        type: "",
        deptIds: [],
      },
      // 数据权限
      dataPermissionTypeOptions: [],
      // 性别
      userGenderOptions: [],
      // 数据权限选中数据
      dataAccessChecked: [],
      // 数据权限弹窗开关
      dataAccessDialogVisible: false,
      // 所属应用当前行信息
      currentAppObj: null,
    };
  },
  computed: {
    drawTitle() {
      return `${this.currentRowObj ? (this.isCheck ? "查看" : "修改") : "新增"}用户`;
    },
  },
  methods: {
    OrganizeTree,
    /**
     * 初始化弹窗
     */
    async initForm() {
      try {
        this.wrapperLoading = true;
        const [dictData, userDetail] = await Promise.all([
          this._DictKeys(),
          this.currentRowObj && this._UserDetail(),
        ]);
        this.dictDataFormat(dictData);
        await this.$nextTick();
        if (this.currentRowObj) {
          this.userDetailFormat(userDetail);
        } else {
          this.userPermObj.type = "1";
          // 设置默认选中地区
          this.ruleForm.dept = this.deptStr;
        }
      } catch (e) {
        console.log(e);
      } finally {
        this.wrapperLoading = false;
      }
    },
    /**
     * 提交
     */
    submitData() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          try {
            this.postDataValidate();
            this.btnLoading = true;
            if (this.currentRowObj) {
              // 修改
              this._UserUpdate();
            } else {
              // 新增
              this._UserAdd();
            }
          } catch (e) {
            this.$message.error(e.message);
          }
        } else {
          this.btnLoading = false;
          return false;
        }
      });
    },
    /**
     * 新增
     */
    async _UserAdd() {
      try {
        await UserAdd(this.getSubmitParams());
        this.$message.success("用户添加成功");
        this.$emit("success");
        this.close();
      } catch (e) {
        console.log(e);
      } finally {
        this.btnLoading = false;
      }
    },
    /**
     * 编辑
     */
    async _UserUpdate() {
      try {
        await UserUpdate(this.getSubmitParams());
        this.$message.success("用户修改成功");
        this.$emit("success");
        this.close();
      } catch (e) {
        console.log(e);
      } finally {
        this.btnLoading = false;
      }
    },
    /**
     * 获取提交参数
     */
    getSubmitParams() {
      const { dept, ...obj } = this.ruleForm;
      let [{ value, name }] = JSON.parse(dept);
      const a = {
        ...obj,
        roleIds: this.roleIds,
        userPerm: this.userPermObj,
        deptId: value,
        deptName: name,
      };
      return a;
    },
    /**
     * 提交数据的验证
     */
    postDataValidate() {
      this.roleDataValidate();
      this.dataAccessValidate();
    },
    /**
     * 角色数据验证
     */
    roleDataValidate() {
      const roleIds = this.$refs.addRole.getRoleIdList();
      if (!roleIds.length) {
        throw new Error("请选择角色");
      }
      this.roleIds = roleIds;
    },
    /**
     * 数据权限数据验证
     */
    dataAccessValidate() {
      if (this.userPermObj === null) {
        throw new Error("请配置数据权限");
      }
    },

    /**
     * 获取数据字典
     */
    async _DictKeys() {
      try {
        const tempArr = ["user_type", "data_permission_type", "user_gender"];
        const data = await DictKeys(tempArr.join());
        return data;
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 数据字典数据格式化
     */
    dictDataFormat(data) {
      if (data) {
        const { data_permission_type: dataPermissionType, user_gender: userGender } = data;
        this.dataPermissionTypeOptions = dataPermissionType;
        this.userGenderOptions = userGender;
      }
    },
    /**
     * 获取用户详情
     */
    async _UserDetail() {
      try {
        const data = await UserDetail(this.currentRowObj.id);
        return data;
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 用户详情数据格式化
     */
    async userDetailFormat(data) {
      if (data) {
        const { userPerm, userRoleList, ...obj } = data;
        const { deptId, deptName } = obj;
        this.$refs.addRole.setCheckedRoleList(userRoleList);
        Object.assign(this.ruleForm, obj);
        let dept = [
          {
            value: deptId,
            name: deptName,
          },
        ];
        this.ruleForm.dept = JSON.stringify(dept);
        this.userPermObj.type = userPerm.type + "";
        if (userPerm.deptIds) {
          this.userPermObj.deptIds = userPerm.deptIds;
          this.$refs.dataAccess && this.$refs.dataAccess.userOrgPermListFormat({ userPerm });
        }
      }
    },
    /**
     * 数据权限的切换
     */
    radioChange(val) {
      // 指定时候弹出框
      this.userPermObj.type = val;
    },
    /**
     * 数据权限弹窗回调
     */
    dataAccessSuccess(val) {
      const { checkedKeys } = val;
      this.userPermObj.deptIds = checkedKeys;
    },
    /**
     * 数据权限，指定弹窗
     */
    doModify(row) {
      const { deptIdList } = row;
      if (this.currentRowObj && !row.hasChanged) {
        this.currentAppObj = {
          ...row,
          id: this.currentRowObj.id,
          deptIds: this.userPermObj.deptIds,
        };
      } else {
        this.currentAppObj = null;
        this.dataAccessChecked = deptIdList;
      }
      this.dataAccessDialogVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.user-dialog {
  ::v-deep .last-label {
    &.el-radio {
      margin-right: 15px;
    }
  }
}
</style>
